<template>
  <div class="comment-display">
    <el-avatar :size="40" :src="comment.user?.avatar" style="margin-right: 12px; flex-shrink: 0;">
      <el-icon><User /></el-icon>
    </el-avatar>
    <div class="comment-main">
      <div class="comment-header">
        <span class="username">{{ comment.user?.username || '匿名用户' }}</span>
        <span class="timestamp">{{ formatDate(comment.createdAt) }}</span>
        <span v-if="comment.isEdited" class="edited-tag">(已编辑)</span>
      </div>
      <div class="comment-content">
        <p v-if="!isEditing">{{ comment.text }}</p>
        <el-input
            v-else
            v-model="editedContent"
            type="textarea"
            :rows="2"
            resize="none"
            class="edit-textarea"
        />
      </div>
      <div class="comment-actions">
        <el-button
          type="text"
          size="small"
          @click="toggleLike"
          :class="{ liked: isLikedByCurrentUser }"
          :loading="liking"
          :disabled="!currentUserId"
        >
          <el-icon><Star v-if="!isLikedByCurrentUser" /><StarFilled v-else /></el-icon>
          {{ likesCount }}
        </el-button>
        <el-button type="text" size="small" @click="emit('reply', comment)" :disabled="!currentUserId">回复</el-button>
        <!-- 编辑和删除按钮仅对评论作者显示 -->
        <template v-if="currentUserId && currentUserId === comment.user?._id">
             <el-button v-if="!isEditing" type="text" size="small" @click="startEditing">编辑</el-button>
             <template v-else>
                 <el-button type="text" size="small" @click="saveEdit" :loading="savingEdit">保存</el-button>
                 <el-button type="text" size="small" @click="cancelEdit">取消</el-button>
             </template>
             <el-button type="text" size="small" @click="emit('delete', comment)">删除</el-button>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import axios from '@/services/axios'
import { Star, StarFilled, User } from '@element-plus/icons-vue';
import { formatDate } from '@/utils/formatters';

const props = defineProps({
  comment: {
    type: Object,
    required: true
  },
  currentUserId: {
    type: String,
    default: null
  }
});

const emit = defineEmits(['reply', 'edit', 'delete', 'toggle-like', 'comment-updated']);

const liking = ref(false);
const isEditing = ref(false);
const editedContent = ref('');
const savingEdit = ref(false);

// 计算当前用户是否点赞了该评论
const isLikedByCurrentUser = computed(() => {
  return props.currentUserId && props.comment.likes?.includes(props.currentUserId);
});

// 计算点赞数
const likesCount = computed(() => props.comment.likes?.length || 0);

// 切换点赞状态
const toggleLike = async () => {
  if (!props.currentUserId) {
    ElMessage.warning('请登录后操作');
    return;
  }
  
  if (liking.value) return;
  
  liking.value = true;
  try {
    const response = await axios.post(`/api/comments/${props.comment._id}/like`);
    emit('toggle-like', {
      commentId: props.comment._id,
      isLiked: response.data.liked,
      likesCount: response.data.likesCount
    });
  } catch (error) {
    console.error('点赞操作失败:', error);
    ElMessage.error(error.response?.data?.error || '操作失败，请稍后重试');
  } finally {
    liking.value = false;
  }
};

// 开始编辑
const startEditing = () => {
  isEditing.value = true;
  editedContent.value = props.comment.text;
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
  editedContent.value = '';
};

// 保存编辑
const saveEdit = async () => {
  if (!editedContent.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }
  if (editedContent.value === props.comment.text) {
    isEditing.value = false;
    return;
  }

  savingEdit.value = true;
  try {
    const response = await axios.patch(`/api/comments/${props.comment._id}`, {
      text: editedContent.value.trim()
    });
    ElMessage.success('评论更新成功');
    isEditing.value = false;
    emit('comment-updated', response.data.comment);
  } catch (error) {
    console.error('更新评论失败:', error);
    ElMessage.error(error.response?.data?.error || '更新评论失败');
  } finally {
    savingEdit.value = false;
  }
};
</script>

<style scoped>
.comment-display {
  display: flex;
  align-items: flex-start;
}

.user-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.comment-main {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.username {
  font-weight: 500;
  font-size: 13px;
  color: #0f0f0f;
  margin-right: 8px;
}

.timestamp {
  font-size: 12px;
  color: #606060;
}

.edited-tag {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.comment-content {
  font-size: 14px;
  line-height: 1.6;
  color: #0f0f0f;
  white-space: pre-wrap;
  margin-bottom: 8px;
}

.edit-textarea {
  margin-bottom: 8px;
}

.comment-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.comment-actions .el-button {
  padding: 4px 8px;
}

.comment-actions .el-button.liked {
  color: #409EFF;
}

.comment-actions .el-icon {
  margin-right: 4px;
}
</style>